"use strict";

/**
 * @ngdoc service
 * @name jgappApp.pageservice
 * @description
 * # pageservice
 * Service in the jgappApp.
 */
angular
  .module("jgappApp")
  .service("PagingService", function ($http, Util, $filter) {
    var Pagingservice = function (url, options, config) {
      this.items = [];
      this.porlist = {};
      this.valuePropertys = {};
      this.busy = false;
      this.limit = 10;
      this.start = 0;
      this.page = 1;
      this.noData = true;
      this.tip = "";
      this.url = url;
      this.options = options || {};
      this.nextPage();
      this.count = 0;
      this.title = "";
      this.config = config || {};
    };
    Pagingservice.prototype.nextPage = function () {
      if (!this.noData) {
        return;
      }
      if (this.busy) {
        return;
      }
      this.busy = true;
      this.options.limit = this.options.limit || this.limit;
      this.start = (this.page - 1) * this.options.limit;
      this.options.start = this.start;
      this.options.startIndex = this.start;
      this.options.page = this.page;
      this.options.endIndex = this.start + this.limit;
      $http
        .get(this.url, {
          params: this.options,
        })
        .then(
          function (data, status, headers, config) {
            data = data.data;
            if (data.logout) {
              Util.logout();
              return;
            }
            var items = data.dataList;
            if (items) {
              for (var i = 0; i < items.length; i++) {
                this.items.push(items[i]);
              }
            }
            this.porlist = data.displayPropertys || this.config.porlist;
            this.valuePropertys = data.valuePropertys;

            if (data.success) {
              // 获取搜索关键字
              this.title = data.searchName || this.config.searchName;
              // 如果没有数据则返回
              if (data.dataList && data.dataList.length > 0) {
                var items = data.dataList;
                this.count = data.totalCount;
                this.page++;
                if (this.items.length === this.count) {
                  this.noData = false;
                  if (this.items.length < 1) {
                    this.tip = "";
                  }
                }
                if (this.options.callback) {
                  this.options.callback(this.items);
                }
              } else {
                this.noData = false;
                this.tip = "";
              }
            } else {
              this.noData = false;
              this.tip = "";
            }
            this.busy = false;
          }.bind(this),
          function (data, status, headers, config) {
            Util.Toast("无法连接到服务器");
          }.bind(this)
        );
    };
    return Pagingservice;
  });
